package gpsFeeder.pkg;


import java.util.HashMap;
import gpsFeeder.pkg.R;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Chronometer;
import android.widget.Chronometer.OnChronometerTickListener;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.ToggleButton;

public class GPSFeederActivity extends Activity implements OnClickListener {
	
	String Time;								//Time  in the format of MM:SS of when the location update was acquired.
	private long countUp; 						//Chronometer timer in milliseconds from the time it starts counting.
	private String Seconds,Minutes;
	private Chronometer chronoTimer;			//Chronometer handler
	
	protected double lat, lon;					//Latitude, Longitude values.
	protected float accuracy;
	private LocationManager myLocManager; 		//Handler of which Android location services will be addressed to.
	private myLocationListener myLocListener;  	//Handler of location updates from android will be registered to.
	private long minTime = 60000; 				//Minimum elapsed time to give location update is one minute in ms
	private float minDist = 15; 				//Minimum distance to give location update is 15 meters
	private String provider; 					//Location provider (GPS/APGS/CELL-ID..etc)
	
	//Criteria crta = new Criteria(); 
	//crta.setAccuracy(Criteria.ACCURACY_FINE); //ACCURACY_FINE = GPRS eventually.  
	//crta.setAltitudeRequired(false);
	//crta.setBearingRequired(false);
	//crta.setPowerRequirement(Criteria.POWER_LOW);
	//String provider = locationManager.getBestProvider(crta, true); //This block would let the application decide what is the best location provider to use based on the pre-set criteria.
	
	BroadcastReceiver batteryReceiver;			//Battery service handler
	int level, voltage, scale, initVoltage;		//Battery level,voltage and scale (maximum).
    IntentFilter filter;						//Intentfilter for the battery broadcast
	
    private ToggleButton switchButton;
	private RadioGroup radioGroup;
	private RadioButton radio1, radio2;
	
	HashMap<String, String> map = new HashMap<String,String>();

	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
     
    
    @Override
    public void onClick(View v) { //handles everybutton's action 
    
        switch( v.getId() )
        {
            case R.id.switchButton:
                
            	switchButton = (ToggleButton) findViewById(R.id.switchButton);
            	if( switchButton.isChecked() == true )
                {
                	//disable radio selection when activated
            		radio1 = (RadioButton) findViewById(R.id.singlePhase);
            		radio2 = (RadioButton) findViewById(R.id.dualPhase);
            		radio1.setEnabled(false);
            		radio2.setEnabled(false);
        
            		
            		//set the fixture phase
            		radioGroup = (RadioGroup) findViewById(R.id.RadioGroup01);
            		switch( radioGroup.getCheckedRadioButtonId() )
            		{
            			case R.id.singlePhase:
            		
            				provider = LocationManager.NETWORK_PROVIDER;
            				this.startProcedure(provider);
            				
            				break;
            		
            			
            			case R.id.dualPhase:
                		
            				provider = LocationManager.GPS_PROVIDER;
            				this.startProcedure(provider);
            				
            				break;
            				
            		default:
                       break;
            		}
                
                } else {	// switchButton is false, turned off.
                
                		//get current device capacity in voltages?
                		//get application power consumption in percentage from android system?
                		//multiple percentage with delta of voltages consumed?
                		chronoTimer.stop();
                		radio1.setEnabled(true);
                		radio2.setEnabled(true);
                		this.cleanUp();
                		
                    	Toast.makeText( getApplicationContext(), "Updates Disabled after "+Time, Toast.LENGTH_SHORT).show();   
                	}
            	
                	break;
                
                // no more buttons to switch to.
            default:
                break;
        }
		
	}
   
     
    public void startProcedure(String provider){
    	
    	//Start the timer...
		this.startTimer(R.id.chronometer1);
		
		//get current battery voltage
		 this.getBatteryConsumption();
		 
		//register listener object with Android Network location service for updates on location change
		getLocation(provider);
		Toast.makeText( getApplicationContext(), "Updates Enabled", Toast.LENGTH_SHORT).show();
    }
    
    
    public void getLocation(String provider) {
    	if (provider == LocationManager.NETWORK_PROVIDER) {
    		myLocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);								//get Android location service
    		myLocListener = new myLocationListener();														
    		myLocManager.requestLocationUpdates( provider, minTime, minDist, myLocListener);
    	}
    	else if (provider == LocationManager.GPS_PROVIDER) {
    		myLocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);								//get Android location service
    		myLocListener = new myLocationListener();														
    		myLocManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, minTime, minDist, myLocListener);
    		if (accuracy >= 35) {
    			//timer1=new Timer();
    	        //timer1.schedule(new GetLastLocation(), 20000); //fetch last known location every 20 seconds. laish?
    			myLocManager.requestLocationUpdates(provider, minTime, minDist, myLocListener); //register listening for GPS fix.
    			}
    	}
    }
    
    
     public void getBatteryConsumption() {
	 BroadcastReceiver batteryReceiver = new BroadcastReceiver() {
	        @Override
	        public void onReceive(Context context, Intent intent) {
				//if (flag = true) { initVoltage = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); } 
	            level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
	            scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
	            voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1);
	        }
	    };
	    filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
	    registerReceiver(batteryReceiver, filter);
	}
    
     
    public void startTimer(int v) {
    	chronoTimer = (Chronometer) findViewById(v);
    	chronoTimer.setBase(SystemClock.elapsedRealtime());
    	chronoTimer.start();
    	chronoTimer.setOnChronometerTickListener(new OnChronometerTickListener(){
            @Override
            public void onChronometerTick(Chronometer arg0) {
                countUp = (SystemClock.elapsedRealtime() - arg0.getBase()) / 1000;
                if (countUp/60 < 10) { Minutes = "0"+ countUp/60;} else { Minutes = ""+ countUp/60;}
                if (countUp%60 < 10) { Seconds = "0"+ countUp%60;} else { Seconds = ""+ countUp%60;}
                Time = Minutes + ":" + Seconds;
                arg0.setText(Time);
            	}
        });
        
    }


    private void cleanUp(){
    	myLocManager.removeUpdates(myLocListener);
    	myLocListener = null;
    	myLocManager = null;
    	
    	//filter = null;
	    unregisterReceiver(batteryReceiver);
	    //batteryReceiver = null;
    }
    
    
    @Override
    protected void onDestroy() {
    	chronoTimer = null;
    	this.cleanUp();
    	this.finish();
    	super.onDestroy();
    }
    
    
    /* Request updates at startup */
	@Override
	protected void onResume() {
		super.onResume();
		getLocation(provider);
	}

	
	@Override
	protected void onPause() {
		super.onPause();
		this.cleanUp();
	}
	
    
    public void showMAP(View v) {
    	String geoURI = "geo:"+lat+","+lon+"?z=20";
    	Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(geoURI));
    	startActivity(i); 	
    	   }
    

    
    public class myLocationListener implements LocationListener {

    	@Override
    	public void onLocationChanged(Location location) {
    		
    		if (location != null) {
            	lat = location.getLatitude();
            	lon = location.getLongitude();
            	accuracy = location.getAccuracy();
            	
            	map.put("Time", Time);
            	map.put("Prov", provider);
            	map.put("Lat", "" + lat);
            	map.put("Lon", "" + lon);
            	Toast.makeText( getApplicationContext(),"By "+map.get("Prov")+" on "+Time+","+accuracy+"accurate.", Toast.LENGTH_SHORT ).show();  //TODO REMOVE: Temporary.
            	
            	if (accuracy <= 35) {
            		switchButton.toggle();
            	}
    		}	
    	}


    	@Override
    	public void onProviderDisabled(String provider) {
    		// TODO Auto-generated method stub
    		Toast.makeText(getApplicationContext(), "GPS Disabled", Toast.LENGTH_SHORT ).show();	// TODO REMOVE: Temporary.
    	}


    	@Override
    	public void onProviderEnabled(String provider) {
    		// TODO Auto-generated method stub
    		Toast.makeText(getApplicationContext(), "GPS Enabled", Toast.LENGTH_SHORT).show();	//TODO REMOVE: Temporary.
    		
    	}


    	@Override
    	public void onStatusChanged(String provider, int status, Bundle extras) {
    		// TODO Auto-generated method stub
    		
    	}
   	
    } //End of MyLocationListener inner class.
    
    
}